import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (
      response.status === 200 ||
      response.status === 201 ||
      response.status === 204
    ) {
      return response
    }
  },
  error => {
    const err = error.response
    if (
      err.status === 500 ||
      (err.status === 401 && err.data.message === '用户名或密码错误')
    ) {
      Message({
        message: err.data.message,
        type: 'error',
        duration: 5 * 1000
      })
    } else if (err.status === 401 && err.data.message === 'Token has expired') {
      // 过期 先调用刷新接口
      const url = error.config.url
      const method = error.config.method
      service.request({
        url: '/api/authorizations/current',
        method: 'put'
      }).then(res => {
        const response = res.data
        store.dispatch('saveToken', { token: response.access_token, time: response.expires_in })
        // 再次调用之前的请求接口
        return service({ url, method }).then(res => {
          return res
        })
      })
    } else if (err.status === 422) {
      Message({
        message: err.data.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
